<template>
  <div class="app-container">
    <div class="container">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="form.productName" />
        </el-form-item>
        <el-form-item label="商品类别">
          <el-select v-model="form.categoryType" placeholder="请选择活动区域">
            <template v-for="item in categoryList">
              <el-option :key="item.id" :label="item.categoryName" :value="item.categoryType" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.productPrice" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="form.productStock" />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-radio-group v-model="form.productStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品小图">
          <el-upload
            id="test"
            ref="“test”"
            :action="upLoadUrl"
            list-type="picture-card"
            :file-list="productIconList"
            :on-success="handleAvatarSuccessIcon"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveIcon"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图">
          <el-upload
            :action="upLoadUrl"
            list-type="picture-card"
            :file-list="form.productImgList"
            :on-success="handleAvatarSuccessImg"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveImg"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="描述 ">
          <el-upload
            :action="upLoadUrl"
            list-type="picture-card"
            :file-list="form.productDescribeList"
            :on-success="handleAvatarSuccessDes"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveDec"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="商品参数">
          <el-button type="primary" @click="add">添加</el-button>
          <el-row>
            <el-col v-for="(item,index) in form.productParameterList" :key="index" :span="24">
              <el-row :gutter="20" class="margins" style="margin-top: 20px">
                <el-col :span="6">
                  <el-input v-model="item.parameterName" placeholder="请输入参数名" type="text" /></el-col>
                <el-col :span="6">
                  <el-input v-model="item.parameterValue" placeholder="请输入参数值" type="text" /></el-col>
                <el-col :span="6">
                  <el-button type="danger" @click="del(index)">删除</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveProduct()">提交</el-button>
          <el-button @click="goToProduct">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { saveProduct, queryProductInfo, queryCategory } from '@/api/product'
export default {
  name: 'Index',
  data() {
    return {
      upLoadUrl: process.env.VUE_APP_BASE_API + 'product-info/upload',
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      productIconList: [],
      categoryList: [],
      fileList: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }, { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
      form: {
        productId: this.$route.query.productId ? this.$route.query.productId : '',
        flag: '1',
        productName: '',
        categoryType: '',
        productPrice: '',
        productStock: '',
        productStatus: '0',
        productIcon: '',
        productImgList: [],
        productDescribeList: [],
        productParameterList: []
      }
    }
  },
  watch: {
    'productIconList': function(newVal) {
      const obj = document.getElementById('test').getElementsByClassName('el-upload--picture-card')
      if (newVal.length > 0) {
        obj[0].style.display = 'none'
      } else {
        obj[0].style.display = 'block'
      }
    }
  },
  mounted() {
    this.queryCategory()
    const productId = this.$route.query.productId
    if (productId) {
      // 编辑
      this.form.flag = '2'
      // 回写
      this.queryProductInfo(productId)
    } else {
      // 新增
    }
    console.log(productId)
  },
  methods: {
    onSubmit() {
      console.log('submit!')
    },
    handleRemoveIcon(file, fileList) {
      const obj = document.getElementById('test').getElementsByClassName('el-upload--picture-card')
      obj[0].style.display = 'block'
      this.productIconList = fileList
      this.form.productIcon = ''
    },
    handleRemoveImg(file, fileList) {
      this.form.productImgList = fileList
    },
    handleRemoveDec(file, fileList) {
      this.form.productDescribeList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 删除参数
    del: function(index) {
      this.form.productParameterList.splice(index, 1)
    },
    // 添加参数
    add: function() {
      const cope = {
        parameterName: '',
        parameterValue: ''
      }
      this.form.productParameterList.push(cope)
    },
    test() {
      console.log(this.fileList)
    },

    // 上传成功回调
    handleAvatarSuccessIcon(res, file) {
      const obj = document.getElementById('test').getElementsByClassName('el-upload--picture-card')
      obj[0].style.display = 'none'
      const data = {
        uid: file.uid,
        name: file.name,
        url: res.data
      }
      this.productIconList.push(data)
      this.form.productIcon = this.productIconList[0].url
    },
    /**
     * 轮播图
     * @param res
     * @param file
     */
    handleAvatarSuccessImg(res, file) {
      const obj = {
        uid: file.uid,
        name: file.name,
        url: res.data
      }
      this.form.productImgList.push(obj)
    },

    /**
     * 描述
     * @param res
     * @param file
     */
    handleAvatarSuccessDes(res, file) {
      const obj = {
        uid: file.uid,
        name: file.name,
        url: res.data
      }
      this.form.productDescribeList.push(obj)
    },
    saveProduct() {
      debugger
      const productImgList = []
      for (let i = 0; i < this.form.productImgList.length; i++) {
        productImgList.push({
          productPath: this.form.productImgList[i].url,
          ordinal: i
        })
      }
      this.form.productImgList = productImgList
      const productDescribeList = []
      for (let i = 0; i < this.form.productDescribeList.length; i++) {
        productDescribeList.push({
          productPath: this.form.productDescribeList[i].url,
          ordinal: i
        })
      }
      this.form.productDescribeList = productDescribeList
      for (let i = 0; i < this.form.productParameterList.length; i++) {
        this.form.productParameterList[i].ordinal = i
      }
      // console.log(this.form)
      saveProduct(this.form).then(response => {
        console.log(response)
        this.$router.push({ path: '/product/index' })
      })
    },
    queryProductInfo(id) {
      queryProductInfo(id).then(response => {
        console.log(response)
        const data = response.data
        const obj = {
          flag: '2',
          productId: data.productInfo.productId,
          productName: data.productInfo.productName,
          categoryType: data.productInfo.categoryType,
          productPrice: data.productInfo.productPrice,
          productStock: data.productInfo.productStock,
          productStatus: data.productInfo.productStatus.toString(),
          productIcon: data.productInfo.productIcon,
          productImgList: this.newArr(data.productImgList),
          productDescribeList: this.newArr(data.productDescribeList),
          productParameterList: data.productParameterList
        }
        this.productIconList = [{ url: data.productInfo.productIcon }]
        this.form = obj
      })
    },
    newArr(arr) {
      const list = []
      for (let i = 0; i < arr.length; i++) {
        list.push({ url: arr[i].productPath })
      }
      return list
    },
    queryCategory() {
      queryCategory().then(response => {
        this.categoryList = response.data
      })
    },
    goToProduct() {
      this.$router.push({ path: '/product/index' })
    }
  }
}
</script>

<style scoped>
  .container{
    height: 100%;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
